package com.zhongyu.controller;



import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@Slf4j
public class LoginController extends HttpServlet {



    @GetMapping(value = {"/login","/"})
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String userCode, String password) {
        Subject subject = SecurityUtils.getSubject();//程序入口
        UsernamePasswordToken token = new UsernamePasswordToken(userCode, password);
        subject.login(token);
        return "redirect:/index";


    }

    @ExceptionHandler({RuntimeException.class})
    public String  handleException(RuntimeException ex, Model model){//捕获异常
        //登录失败
        String loginErr="";
    if (ex instanceof UnknownAccountException){//未知的账号用户名错误
        loginErr="用户名或密码错误！";
    }else if (ex instanceof IncorrectCredentialsException){//密码错误异常
        loginErr="用户名或密码错误！";
    }else {
        loginErr="系统错误，请联系管理员!";
        log.error(loginErr,ex);
        /* ex.printStackTrace();*/
    }
model.addAttribute("loginErr",loginErr);
    return "login";
    }

}
